package com.lzh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lzh.oss.service.FileService;
import com.lzh.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @ClassName FileServiceImpl
 * Description
 * @Author lizihao
 * Date 2020/11/26 16:19
 * @Version 1.0
 **/
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

//        String uploadUrl = null;

        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

// 上传文件流。
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();

            String uuid = UUID.randomUUID().toString().replaceAll("-","");

            filename = uuid+filename;

            String date = new DateTime().toString("yyyy/MM/dd");

            filename = date+"/"+filename;
            ossClient.putObject(bucketName, filename, inputStream);

// 关闭OSSClient。
            ossClient.shutdown();

            String url = "https://"+bucketName+"."+endPoint+"/"+filename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}
